package com.heima.user.service.impl;

import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private CacheService cacheService;

    /**
     * 关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        // 1. 检查参数
        if(dto == null || checkParam(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2. 是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 3. 关注, 保存数据
        if(dto.getOperation() == 0){
            // 关注
            // 将作者写入我的关注中
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION+user.getId(), dto.getAuthorId().toString(), System.currentTimeMillis());
            // 将我写入作者的粉丝中
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION+dto.getAuthorId(), user.getId().toString(), System.currentTimeMillis());
        }else{
            // 取消关注
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION+user.getId(), dto.getAuthorId().toString());
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION+dto.getAuthorId(), user.getId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 检查 UserRelationDto 参数
     * @param dto
     * @return
     */
    private boolean checkParam(UserRelationDto dto) {
        if(dto.getArticleId() == null || dto.getAuthorId() == null){
            return true;
        }
        if(dto.getOperation() > 1 || dto.getOperation() < 0){
            return true;
        }
        return false;
    }
}
